﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using OnlineBookReader;
using HtmlExtractor;
using Reader.Domain;
using SLHtmlExtractor.ObjectOutput;
using HtmlExtractor.Output;
using System.Xml.Linq;
using System.Windows.Markup;
using System.IO;
using System.Xml.XPath;
using ImageTools.Controls;

namespace Reader.View
{
    [Sample("章节", "chapter")]
    public partial class ChapterView : OnlineXamlView
    {
        public ChapterView()
        {
            InitializeComponent();
        }
        public string CurrentUri { get; set; }

        public ChapterView(string uri)
            : this()
        {
            CurrentUri = uri;
            this.DataContext = this;
        }
        string template = @"View/Chapter/xamltextchapter.xml";
        protected override XDocument GenerateXaml(string html, string uri, string template)
        {
            return BookChapter.GenerateChapterXaml(html, uri, template);
        }
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
        }
        ScrollViewer chapter=null;
        HyperlinkButton Previous;
        HyperlinkButton Next;
        string NextUri;
        string PreviousUri;
        protected override void SetElement(XDocument rdoc)
        {
           
            chapter = (ScrollViewer)XamlReader.Load(rdoc.ToString());
            Previous = (HyperlinkButton)chapter.FindName("Previous");
            HyperlinkButton Content = (HyperlinkButton)chapter.FindName("Content");
            Next = (HyperlinkButton)chapter.FindName("Next");
            NextUri = Next.CommandParameter.ToString();
            PreviousUri = Previous.CommandParameter.ToString();
            Cache.Current.Add("NextChapterUri", NextUri);
            Cache.Current.Add("PreChapterUri", PreviousUri);
            Cache.Current.Add("NextChapter", Next);
            Cache.Current.Add("PreChapter", Previous);
            //判断是否是起点
            if (Uri.IsWellFormedUriString(CurrentUri,UriKind.Absolute))
            {
                if (new Uri(CurrentUri).Host.Contains("qidian.com"))
                {
                    if(Uri.IsWellFormedUriString(BookChapter.GetTextUri(rdoc),UriKind.Absolute))
                        LoadQidianXaml(BookChapter.GetTextUri(rdoc), template);
                    else
                    {
                        RichTextBox textContent = (RichTextBox)chapter.FindName("TextContent");
                        if (textContent != null)
                            textContent.Visibility = Visibility.Visible;
                    }
                }
                else
                {
                    RichTextBox textContent = (RichTextBox)chapter.FindName("TextContent");
                    if (textContent != null)
                        textContent.Visibility = Visibility.Visible;
                }
            }
         
            chapter.GotFocus += new RoutedEventHandler(chapter_GotFocus);
            chapteContainer.Content = chapter;
            StackPanel imageContent = (StackPanel)chapter.FindName("ImageContent");
            string bookName=BookChapter.GetBookName(rdoc);
            foreach (UIElement ui in imageContent.Children)
            {
                AnimatedImage ai = ui as AnimatedImage;
                if (!string.IsNullOrEmpty(ai.Source.ToString()))
                {
                    string uri = ai.Source.ToString();
                    string localFileName=null;
                    if ((Cache.Current.TryGet(uri, out localFileName))||(ReaderConfig.IsUseLoaclBook && ReaderPath.TryGetSiteFileName(uri, out localFileName)))
                    {
                        try
                        {
                            if (Context.IsLoacalFile(localFileName))
                            {
                                ImageTools.Image image = new ImageTools.Image();
                                image.IsLoadingSynchronously = true;
                                image.SetSource(File.OpenRead(localFileName));
                                ai.Source = image;
                            }
                        }
                        catch (Exception ex)
                        { }
                    }
                    else
                    {
                        ai.Source = uri;
                    }

                }
            }

            if (Uri.IsWellFormedUriString(NextUri, UriKind.Absolute))
            {
                if (NextUri == Content.CommandParameter.ToString() || QidianUtil.IsVipUri(NextUri))
                {
                    //http://www.qidian.com/BookReader/BuyChapterUnLogin.aspx?bookId=107580&amp;chapterId=20903393
                    Next.IsEnabled = false;
                }
                else
                {
                    BookChapter.WriteChapterCache(NextUri, template, ReaderConfig.AutoReadChapter, true);
                }
            }
            else
                Next.IsEnabled = false;

            if (Uri.IsWellFormedUriString(PreviousUri, UriKind.Absolute))
            {
                if (PreviousUri == Content.CommandParameter.ToString())
                {
                    Previous.IsEnabled = false;
                }
                else
                {

                    BookChapter.WriteChapterCache(PreviousUri, template, ReaderConfig.AutoReadChapter, false);
                }
            }
            else
                Previous.IsEnabled = false;
            
        }
        protected override void SetQidianElement(XDocument rdoc)
        {
            RichTextBox tempParas = (RichTextBox)XamlReader.Load(BookChapter.GetTextContent(rdoc).ToString());
            tempParas.Visibility = Visibility.Visible;
            StackPanel content = (StackPanel)chapter.FindName("BookContent");
            content.Children.Insert(3, tempParas);
         
        }
        void chapter_GotFocus(object sender, RoutedEventArgs e)
        {
           
        }
        private void LoadChapter(string uri)
        {
            
           LoadXaml(uri, template);

           ScrollViewer SampleScroller = ((ScrollViewer)((ContentPresenter)(VisualTreeHelper.GetParent(this))).Parent);
            SampleScroller.KeyUp += new KeyEventHandler(SampleScroller_KeyUp);
            SampleScroller.UpdateLayout();
            SampleScroller.ScrollToTop();
            SampleScroller.Focus();
          
        }

        void SampleScroller_KeyUp(object sender, KeyEventArgs e)
        {
            //一直不是当前页面触发，而是第一次进入的页面触发？？？，读取缓存获取当前页
            HyperlinkButton pre = Cache.Current.Get<HyperlinkButton>("PreChapter");
            HyperlinkButton next = Cache.Current.Get<HyperlinkButton>("NextChapter");

            if (pre != null && next != null)
            {
                //e.Handled = true;
                ScrollViewer SampleScroller = sender as ScrollViewer;
                if (e.Key == Key.Right && next.IsEnabled)
                {
                    string nextUri;
                    if (Cache.Current.TryGet("NextChapterUri", out nextUri))
                    {
                        SampleBrowser.Current.PopulateSamplesTab("chapter", nextUri);
                        // e.Handled = true;
                    }

                }
                if (e.Key == Key.Left && pre.IsEnabled)
                {
                    string preUri;
                    if (Cache.Current.TryGet("PreChapterUri", out preUri))
                    {
                        SampleBrowser.Current.PopulateSamplesTab("chapter", preUri);
                        //e.Handled = true;
                    }
                }

                if (e.Key == Key.Home)
                {
                    SampleScroller.UpdateLayout();
                    SampleScroller.ScrollToTop();
                    //e.Handled = true;
                }
                if (e.Key == Key.End)
                {
                    SampleScroller.UpdateLayout();
                    SampleScroller.ScrollToBottom();
                    //e.Handled = true;
                }
            }
            e.Handled = true;
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if(Uri.IsWellFormedUriString(CurrentUri,UriKind.Absolute))
                LoadChapter(CurrentUri);
            
        }

        public ICommand OpenChapter
        {
            get
            {
                return new DelegateCommand((parameter) => { SampleBrowser.Current.PopulateSamplesTab("chapter", (string)parameter); }, (o) => { return true; });
               
            }
        }
        public ICommand OpenContent
        {
            get
            {
                return new DelegateCommand((parameter) => { SampleBrowser.Current.PopulateSamplesTab("content", (string)parameter); }, (o) => { return true; });
            }
        }

        private void chapteContainer_GotFocus(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is HyperlinkButton)
            {
                
                return;
            }
            else
            {
                ScrollViewer SampleScroller = ((ScrollViewer)((ContentPresenter)(VisualTreeHelper.GetParent(this))).Parent);
                SampleScroller.Focus();
            }
        }

        private void chapteContainer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
           
            ScrollViewer SampleScroller = ((ScrollViewer)((ContentPresenter)(VisualTreeHelper.GetParent(this))).Parent);
            SampleScroller.Focus();
        }

        private void chapteContainer_KeyDown(object sender, KeyEventArgs e)
        {

        }

      
    }

}
